import org.deltaset.support.gen.AbstractGenWriter;
import org.deltaset.support.meta.MetaModelFactory;

public class LabelWriter extends AbstractGenWriter{

    public boolean isSatisfied(){
        return true;
    }
    
    public void write(){
        if(true==getContext().getOverwrite()){
            return;
        }
        def dsonString = getContext().getCommandContext();
        def model = MetaModelFactory.fromDsonString(dsonString, getContext().getPackageName());
        def baseDir = getContext().getBaseDir();
        LabelWriter.write(baseDir,model);
        model.fields.each{f->
            if(!f.fields.isEmpty()){
                LabelWriter.write(baseDir,f);
            }
        }
    }
    
    static void write(baseDir, model){        
        def labelDir = "/src/main/resources/${model.packageName}".replace( '.', '/' )
        File outputDir = new File( baseDir, labelDir )
        outputDir.mkdirs()
        
        
        
        File msgFile = new File( outputDir, "${model.typeClassLike}Messages.properties" );
                        
        msgFile.append("#labels generated for ${model.type}")
        //msgFile.append("\n"+beanlikeDomain+".view.detail=GEN "+classlikeDomain+" detail")
        //msgFile.append("\n"+beanlikeDomain+".view.form=GEN "+classlikeDomain+" form")
        //msgFile.append("\n"+beanlikeDomain+".view.list=GEN "+classlikeDomain+" list")
        msgFile.append("\nview.title = ${model.propertyClassLike}")
        msgFile.append("\nview.plural = ${model.propertyClassLike}s")
        
        model.fields.each{f->
            msgFile.append("\n${f.propertyBeanLike} = ${f.propertyClassLike}");
        }
        
        
        
        //File facesConfigFile = new File( baseDir, "src/main/resources/META-INF/faces-config.xml" );
        File facesConfigFile = new File( baseDir, "/src/main/webapp/WEB-INF/faces-config.xml" );
        def allLines = facesConfigFile.readLines()
        def changedLines=[]
        
        allLines.each{line ->
            if(line.contains("</application>")){
                changedLines.add("        <resource-bundle>")
                changedLines.add("            <var>${model.typeBeanLike}Msg</var>")
                changedLines.add("            <base-name>${model.packageName}.${model.typeClassLike}Messages</base-name>")
                changedLines.add("        </resource-bundle>")                
            }
            changedLines.add(line)
        }
        facesConfigFile.withWriter{file ->
            changedLines.each{line ->
                file.writeLine(line)
            }
        }
    }
}